package com.lemon.smartsafety.ui.activity.fire.item.statistics;

import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.entity.RefreshViewEntity;
import com.lemon.smartsafety.http.HttpBack;
import com.lemon.smartsafety.http.HttpOkBase;
import com.lemon.smartsafety.http.HttpPath;
import com.lemon.smartsafety.result.BaseMode;
import com.lemon.smartsafety.result.fire.FireCompanyBaseScore;
import com.lemon.smartsafety.result.fire.SafeManageDetails;
import com.lemon.smartsafety.result.fire.SuperviseCompanyDetail;
import com.lemon.smartsafety.result.fire.SuperviseCompanyResult;
import com.lemon.smartsafetynew.ui.activity.base.NewBaseActivity;
import com.lemon.smartsafety.ui.activity.fire.FirefightingUtil;
import com.lemon.smartsafety.ui.activity.fire.item.safemanage.FireSafeManageAddActivity;
import com.lemon.smartsafety.ui.activity.fire.item.safemanage.FireSafeManageShowActivity;
import com.lemon.smartsafety.ui.adapter.fire.FirefightingSafeAdapter;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.JsonUtils;
import com.lemon.smartsafety.utils.LogUtils;
import com.lemon.smartsafety.utils.app.ToastUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.view.ViewFireCompanyNone;
import com.lemon.smartsafety.view.ViewFireTop;
import com.lemon.smartsafety.view.list.ListRefreshView;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

public class SafeStatisticsActivity extends NewBaseActivity {

    @Bind(R.id.main_title)
    TextView mainTitle;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @Bind(R.id.textView)
    TextView textView;
    @Bind(R.id.lineAll)
    LinearLayout lineAll;
    @Bind(R.id.listView)
    ListRefreshView listView;
    @Bind(R.id.swipe_layout)
    SwipeRefreshLayout swipeLayout;
    @Bind(R.id.fireTop)
    ViewFireTop fireTop;
    @Bind(R.id.viewFireCompanyNone)
    ViewFireCompanyNone viewFireCompanyNone;


    private FirefightingSafeAdapter firefightingSafeAdapter;
    private List<SafeManageDetails> mList;
    private List<SafeManageDetails> safeManageDetailsList;

    private SuperviseCompanyResult.ResultEntity resultEntity;
    private FireCompanyBaseScore fireCompanyBaseScore;

    private SuperviseCompanyDetail.MyCompanyScoreListEntity myCompanyScoreListEntity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void getBundleArgs() {
        if (getIntent().getExtras() != null) {
            resultEntity = (SuperviseCompanyResult.ResultEntity) getIntent().getSerializableExtra(BundleKey.FIRE_COMPANY_BASE_INFO);
            myCompanyScoreListEntity = (SuperviseCompanyDetail.MyCompanyScoreListEntity) getIntent().getSerializableExtra(BundleKey.FIRE_COMPANY_PRO_CODE);
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_safe_statistics;
    }

    @Override
    protected void initTitleView() {
        setBarTitle("安全管理及时率");
    }

    @Override
    protected void initView() {

        fireTop.setTitleContent(resultEntity.getCompanyName());
        fireTop.setTitleSubContent("");
        fireTop.setNum1Content("0");
        fireTop.setNum2Content("/0");
        fireTop.setNum1Color(R.color.colorAppRed);
        fireTop.setNum2Color(R.color.colorAppBlue);
        fireTop.setImageCircleShow(true);
        fireTop.setImageCircleBg(R.drawable.shape_circle_red);

        textView.setText("安全管理");

        safeManageDetailsList = new ArrayList<>();
        mList = new ArrayList<>();
        firefightingSafeAdapter = new FirefightingSafeAdapter(mActivity, mList);
        firefightingSafeAdapter.setShowArrowRight(false);
        listView.setAdapter(firefightingSafeAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Bundle bundle = new Bundle();
                bundle.putSerializable(BundleKey.FIRE_COMPANY_BASE_INFO, resultEntity);
                bundle.putSerializable(BundleKey.FIRE_COMPANY_SAFE_BASE_INFO, mList.get(position));
                UIHelper.showActivity(mActivity, bundle, FireSafeManageShowActivity.class);

            }
        });
        initLoadeRefresh(listView);
        initSwipRefresh(swipeLayout);
    }

    @Override
    protected void initHttp() {
        initTopHttp();
        initList();
    }

    @Override
    protected void initList() {
        current_page = 1;
        httpList();
        listView.setIsload(true);
    }

    @Override
    protected void loadList() {
        if (mList.size() % page_size == 0) {
            current_page = current_page + 1;
            httpList();
        } else {
            listView.setIsload(false);
        }
    }

    @Subscribe
    public void onEventMainThread(RefreshViewEntity refreshViewEntity) {
        if (refreshViewEntity.getTAG().equals(FireSafeManageAddActivity.class.getName())) {
            initList();
        }
    }


    @Override
    protected void refreshView() {
        if (current_page == 1) {
            mList.clear();
        }
        mList.addAll(safeManageDetailsList);
        firefightingSafeAdapter.notifyDataSetChanged();
    }

    /**
     * 错误的情况下 刷新
     */
    private void errorView(String msg){

        try {
            if (CommonUtil.listIsEmpty(mList)) {
                viewFireCompanyNone.setVisibility(View.VISIBLE);
                listView.setVisibility(View.GONE);
                viewFireCompanyNone.setContent(msg);
                viewFireCompanyNone.setSearch("重试");
                viewFireCompanyNone.setAllClick(new ViewFireCompanyNone.AllClick() {
                    @Override
                    public void click() {
                        LogUtils.LOGE("点击了重试");
                        httpList();
                    }
                });
            } else {
                viewFireCompanyNone.setVisibility(View.GONE);
                listView.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void callFinish() {
        mActivity.finish();
    }


    public void initTopHttp() {
        LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");
        params.put("company_code", resultEntity.getCompanyCode());
        params.put("radio_code", myCompanyScoreListEntity.getTargetCode());

        showLoading("");
        HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Get_score), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                dismissLoading();
                if (httpClient) {
                    BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (HttpBack.httpBackError(baseMode)) {

                            try {
                                fireCompanyBaseScore = mGson.fromJson(mGson.toJson(baseMode.getResult()), FireCompanyBaseScore.class);
                                initTopScore();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        } else {
                            ToastUtil.show(baseMode.getMsg());
                        }
                    }
                }
            }
        });

    }

    /**
     * 初始化顶部信息
     */
    private void initTopScore() {
        fireTop.setNum1Color(FirefightingUtil.getScoreTextColor(fireCompanyBaseScore.getStatus()));
        fireTop.setNum2Color(R.color.colorAppBlue);
        fireTop.setNum1Content(fireCompanyBaseScore.getCompanyScore());
        fireTop.setNum2Content("/" + fireCompanyBaseScore.getAvgScore());
        fireTop.setImageCircleBg(FirefightingUtil.getScoreImgCircleColor(fireCompanyBaseScore.getStatus()));
    }


    private void httpList() {
        if (!bPutHttp) {
            bPutHttp = true;
            LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");
            params.put("page_size", String.valueOf(page_size));
            params.put("current_page", String.valueOf(current_page));
            params.put("company_code", resultEntity.getCompanyCode());

            showLoading("");
            HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Get_safe_manage_details), "", new HttpOkBase.HttpInterface() {
                @Override
                public void callBackFunction(boolean httpClient, String result) {

                    dismissLoading();
                    bPutHttp = false;
                    if (httpClient) {
                        BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                        if (!CommonUtil.objIsEmpty(baseMode)) {
                            if (HttpBack.httpBackError(baseMode)) {

                                try {
                                    safeManageDetailsList = mGson.fromJson(mGson.toJson(baseMode.getResult()), new TypeToken<List<SafeManageDetails>>() {
                                    }.getType());
                                    refreshView();
                                    errorView(baseMode.getMsg());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } else {
                                ToastUtil.show(baseMode.getMsg());
                                errorView(baseMode.getMsg());
                            }
                            firefightingSafeAdapter.notifyDataSetChanged();
                        }
                    }else{
                        safeManageDetailsList=null;
                        errorView("网络连接失败");
                    }
                }
            });
        }

    }


}
